import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { observer } from 'mobx-react';
import { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, message, Tabs } from 'antd';

import { ImageUploader } from '../../components/ImageUploader';
import { StandardPageModel } from '../../../model/content/pages/standard/PageModel';
import { ContentEditor } from './standard/ContentEditor';
import { PRODUCT_PAGE_URL } from '../../../service/Config';

import * as QRCode from 'qrcodejs2';

const FormItem = Form.Item;
const Option = Select.Option;
const InputGroup = Input.Group;
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
const tailFormItemLayout = {
    wrapperCol: {
        span: 14,
        offset: 6,
    },
};

interface PageEditorState {
    store?: StandardPageModel;
    logoFileList?: any[];
    isEditMode?: boolean;
}

@observer
export class PageEditor extends React.Component<RouteComponentProps<any, any>, PageEditorState> {

    private qrcode;

    constructor(props) {
        super(props);
        this.initState();
    }

    initState() {

        let store: StandardPageModel;
        let isEditMode = this.props.route.path !== 'create';

        if (!isEditMode) { // 创建
            store = new StandardPageModel();
        }
        else { // 编辑
            store = new StandardPageModel(this.props.params.id);
            store.fetchData().catch(res => {
                message.error(`数据请求失败`, 2.5);
            });
        }

        this.state = {
            store,
            isEditMode,
            logoFileList: null,
        };
    }

    private onSubmit = () => {
        this.state.store.save().then(
            res => {
                message.success(res.message, 2.5);
                this.setState({ isEditMode: true });
            },
            err => {
                message.error(err.message, 2.5);
            }
        );
    }

    private renderLogoUploader() {
        var {store, logoFileList} = this.state;
        var onChange = (fileList) => this.setState({ logoFileList: fileList });
        var onUpdate = (fileList) => store.data.logo = fileList.length ? fileList[0].url : "";

        if (!logoFileList && store.data.logo) {
            logoFileList = [{
                uid: -1,
                url: store.data.logo
            }];
        }

        return <ImageUploader fileList={logoFileList} onChange={onChange} onUpdate={onUpdate} />;
    }

    private createQRCode(element: HTMLElement) {
        if (!element) {
            this.qrcode && this.qrcode.clear();
            return;
        }

        var url = `${PRODUCT_PAGE_URL}${this.state.store.id}`;

        if (!this.qrcode) {
            this.qrcode = new QRCode(element, {
                text: url,
                width: 128,
                height: 128,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            })
        }
        else {
            this.qrcode.clear();
            this.qrcode.makeCode(url);
        }
    }

    componentWillUnmount() {
        if (this.qrcode) {
            this.qrcode.clear();
            this.qrcode = null;
        }
    }

    render() {
        var {store} = this.state;

        return <Tabs type="card">
            <Tabs.TabPane tab="基础信息" key="1">
                <Form horizontal>
                    <FormItem
                        {...formItemLayout}
                        label="标题"
                        required
                        validateStatus={store.titleValid ? 'success' : 'error'}
                    >
                        <Input value={store.data.title} onChange={e => store.data.title = e.target['value']} placeholder="请输入页面标题，7个字以内" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="分享标题"
                        required
                        validateStatus={store.shareTitleValid ? 'success' : 'error'}
                    >
                        <Input value={store.data.shareTitle} onChange={e => store.data.shareTitle = e.target['value']} placeholder="请输入分享标题，24个字以内" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="分享描述"
                        required
                        validateStatus={store.shareDescValid ? 'success' : 'error'}
                    >
                        <Input value={store.data.shareDesc} onChange={e => store.data.shareDesc = e.target['value']} placeholder="请输入分享描述，35个字以内" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="LOGO图片"
                        required
                        extra="图片建议尺寸：120像素*120像素，正方形"
                    >
                        {this.renderLogoUploader()}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="分类"
                        required>
                        {this.renderCategories()}
                    </FormItem>
                    {this.state.isEditMode &&
                        <FormItem
                            {...formItemLayout}
                            label="页面链接">
                            <div ref={e => this.createQRCode(e)}></div>
                            <span>{`${PRODUCT_PAGE_URL}${store.id}`}</span>
                        </FormItem>}
                    <FormItem {...tailFormItemLayout}>
                        <Button type="primary" size="large" onClick={this.onSubmit} style={{ marginRight: 10 }}>保存</Button>
                        <Button size="large" onClick={() => location.href = '#/content/page/manager'}>返回列表</Button>
                    </FormItem>
                </Form>
            </Tabs.TabPane>
            {
                this.state.isEditMode && <Tabs.TabPane tab="内容编辑" key="2">
                    <ContentEditor store={store} />
                </Tabs.TabPane>
            }
        </Tabs >;
    }

    private renderCategories() {
        var {store} = this.state;

        return store.data.categories.map((category, index) => {
            return <InputGroup size="large" key={index}>
                <Col span={8}>
                    <Input placeholder="请输入分类名称，最多四个字" value={category.name} onChange={e => category.name = e.target['value']} />
                </Col>
                <Col span={4}>
                    {store.data.categories.length < 4 && <Button shape="circle" icon="plus" onClick={() => store.addCategory(index + 1)} />}
                    {store.data.categories.length > 1 && <Button shape="circle" icon="delete" onClick={() => store.deleteCategory(index)} />}
                </Col>
            </InputGroup>
        })
    }
}

